﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BarcodePrint
{
    public class PrintWithCOM
    {
        private string _portName;
        /// <summary>
        /// COM 端口号
        /// </summary>
        public Int32 Port { get; set; }

        public PrintWithCOM(int port)
        {
            this.Port = port;
            this._portName = string.Format("COM{0}", port == 0 ? 1 : port);
        }
        public PrintWithCOM() : this(1) { }

        public bool Print(string cmd)
        {
            byte[] bytes = Encoding.Default.GetBytes(cmd);
            return this.PrintToCOM(bytes);
        }

        public bool Print(byte[] bytes)
        {
            return this.PrintToCOM(bytes);
        }

        private bool PrintToCOM(byte[] bytes)
        {
            bool result = false;
            SerialPort com = new SerialPort(this._portName, 9600, Parity.None, 8, StopBits.One);
            try
            {
                com.Open();
                com.Write(bytes, 0, bytes.Length);
                result = true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
            finally
            {
                if (com.IsOpen)
                {
                    com.Close();
                }
            }
            return result;
        }
    }
}
